package com.zzyl.nursing.service.impl;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.apache.commons.math3.analysis.function.Add;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Collectors;

/**
 * 设备信息Service业务层处理
 *
 * @author wd
 * @date 2025-05-25
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;


    @Autowired
    private IoTDAClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 同步IOT平台产品列表
     */
    @Override
    public void syncProductList() {
        //1. 调用IOT平台接口查询产品列表
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        if(response==null || response.getHttpStatusCode()!=200) {
            throw new BaseException("查询产品列表失败");
        }

        //2. 将产品列表保存到Redis中
        List<ProductSummary> productList = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, JSONUtil.toJsonStr(productList));
    }

    /**
     * 查询产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //1. 从Redis中查询产品列表JSON字符串
        String productListJSON = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        if(StringUtils.isBlank(productListJSON)) {
            throw new BaseException("产品列表不存在");
        }

        //2. 将JSON字符串解析为产品列表
        List<ProductSummary> productSummaryList = JSONUtil.toList(productListJSON, ProductSummary.class);

        //3. 将每个产品类型转为ProductVo
        List<ProductVo> productVoList = productSummaryList.stream().map(x -> {
            return ProductVo.builder().productName(x.getName()).productKey(x.getProductId()).build();
        }).collect(Collectors.toList());

        //4. 返回数据
        return productVoList;
    }
    /**
     * 查询设备信息
     *
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备信息列表
     *
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备信息
     *
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备信息
     *
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备信息
     *
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息信息
     *
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 注册设备
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(DeviceDto dto) {
        // 根据雪花算法生成唯一设备标识码
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        // 设置设备描述（备注）
        String deviceDescription = dto.getRegisterDeviceRequest().getNickname();
        // 判断设备名是否重复
        Long count = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (count>0){
            throw new BaseException("设备名重复");
        }
        // 判断设备标识码是否重复
        Long countNodeId = this.lambdaQuery().eq(Device::getNodeId, nodeId).count();
        if (countNodeId>0){
            throw new BaseException("设备标识码重复");
        }

        // 检查当前位置是否绑定过同类型产品
        Long countLocation = this.lambdaQuery()
                // 位置类型 0随身设备 1 固定设备
                .eq(Device::getLocationType, dto.getLocationType())
                // 绑定位置
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                // 产品key
                .eq(Device::getProductKey, dto.getProductKey())
                .count();
        if (countLocation>0){
            throw new BaseException("当前位置绑定过相同产品");
        }


         /*注册设备*/
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        // 产品key
        addDevice.setProductId(dto.getProductKey());
        // 设备名称
        addDevice.setDeviceName(dto.getDeviceName());
        // 设备描述
        addDevice.setDescription(deviceDescription);
        // 设备标识码
        addDevice.setNodeId(nodeId);

        AuthInfo authInfo = new AuthInfo();
        // 设备密钥
        String secret = IdUtil.simpleUUID();
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);

        addDeviceRequest.setBody(addDevice);
        AddDeviceResponse response = client.addDevice(addDeviceRequest);
        if (response.getHttpStatusCode()!= 201){
            throw new BaseException("华为云IoT注册失败");
        }


        // 注册成功后保存设备信息到数据库
        Device device = new Device();
        BeanUtils.copyProperties(dto,device);
        device.setNodeId(nodeId); // 设备标识码
        device.setIotId(response.getDeviceId()); // 设备id（由华为云IoT平台生成）
        device.setNickname(deviceDescription); // 备注名称
        device.setDeviceDescription(deviceDescription);
        device.setSecret(secret); // 设备密钥
        device.setProductName(this.getProDuctName(dto.getProductKey()));

        this.save(device);
    }

    /**
     * 从缓存中根据产品id获取产品名
     * @param productAppId
     * @return
     */
    private String getProDuctName(String productAppId){

        String productListJson = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        if (StringUtils.isBlank(productListJson)) {
            return null;
        }
        // 解析JSON
        List<ProductSummary> list = JSONUtil.toList(productListJson, ProductSummary.class);
//        System.out.println(list+"============");
        ProductSummary productSummary = list.stream().filter(x->productAppId.equals(x.getProductId()))
                .findFirst().get();

        return productSummary.getName();
    }
    @Autowired
    private ISysUserService userService;
    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;

    /**
     * 获取设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {

        // 先从本地数据库查询
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device==null){
            throw new BaseException("没有查询到设备");
        }

        //
        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtils.copyProperties(device,vo);
        vo.setDeviceSecret(device.getSecret());
        vo.setGmtCreate(device.getCreateTime());
        vo.setCreator(userService.selectUserById(Long.valueOf(device.getCreateBy())).getUserName());
        vo.setRegion(huaWeiIotConfigProperties.getRegionId());


        // 调用华为iot平台接口查询设备
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);

        ShowDeviceResponse response = client.showDevice(request);
        if (response==null){
            throw new BaseException("华为云iot接口调用失败");
        }

        BeanUtils.copyProperties(response,vo);
        vo.setDeviceStatus(response.getStatus());

        String activeTime = response.getActiveTime();
        if (StringUtils.isNotBlank(activeTime)){
            LocalDateTime gmtActive = OffsetDateTime.parse(activeTime).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            vo.setGmtActive(gmtActive);
        }
        if (StringUtils.isBlank(response.getFwVersion())){
            vo.setFirmwareVersion(response.getFwVersion());
        }


        return vo;
    }


    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param productKey
     * @return
     */
    @Override
    public JSONObject  queryProductModelInfo(String productKey) {

        if (StringUtils.isEmpty(productKey)){
            throw new BaseException("参数为空");
        }

        //调用华为云iot接口查询数据
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response  = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("调用华为云接口失败");
        }
        JSONObject productModelInfo = null;

        // 判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollUtil.isNotEmpty(serviceCapabilities)){
            productModelInfo = JSONUtil.parseObj(serviceCapabilities.get(0));
        }


        return productModelInfo;
    }


    /**
     * 查询设备上报的数据
     * @param deviceName
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus( String deviceName) {


        // 判断设备是否存在
        Device device = this.lambdaQuery().eq(Device::getDeviceName, deviceName).one();
        if (device ==null ){
            throw new BaseException("设备不存在");
        }
        String deviceId = device.getIotId();

        // 调用华为云接口查询影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(deviceId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response==null || response.getHttpStatusCode() != 200){
            throw new BaseException("或华为云接口调用失败");
        }

        // 解析封装响应结果
        List<DeviceShadowData> shadowDataList = response.getShadow();
        if (CollUtil.isEmpty(shadowDataList)){
            throw new BaseException("影子数据为空");
        }
        DeviceShadowData shadowData = shadowDataList.get(0);
        DeviceShadowProperties reported = shadowData.getReported();
        List<Map<String,Object>> list = new ArrayList<>();
        String eventTimeStr = reported.getEventTime();// 数据上报时间
        // 时间格式转换
        LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());

        jsonObject.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("identifier",k);
            map.put("value",v);
            map.put("time",eventTime);
            list.add(map);
        });

        Map<String,Object> propertyStatusInfo = new HashMap<>();
        propertyStatusInfo.put("propertyStatusInfo", list);

        Map<String,Object> result = new HashMap<>();
        result.put("list",propertyStatusInfo);

        return AjaxResult.success(result);
    }
}
